#ifndef USBKEYBOARDTHREAD_H
#define USBKEYBOARDTHREAD_H

#include <QObject>
#include <QMutex>
#include <QDebug>
#include "libusb.h"
#include <QThread>
#include <QElapsedTimer>

enum receicerFuntion {
    POLL_KEYBOARDDATA,
    CONNECT_KBDEVICE,
    RELEASE_KBDEVICE,
    RECONNECT_KBDEVICE,
    SENDDATATO_KBDEVICE
};

class UsbKeyboardThread : public QObject
{
    Q_OBJECT
public:
    explicit UsbKeyboardThread(QObject *parent = nullptr);
    ~UsbKeyboardThread();
    bool GetReadLoopState(){return running;}
    int getOpendevice_flag(){return opendevice_flag;}
    int getClaimInterface_flag(){return ClaimInterface_flag;}

    void perform(receicerFuntion funtion);
    void start();
    void init();
    void stop();

    bool getKBConnectStatus(){return KBConnectDongleStatus;}

signals:
    void startReading();
    void KBdataReceived(const QByteArray &data);
    void TPdataReceived(const QByteArray byteArray);
    void dataReceived(const QByteArray byteArray);
    void KTdataReceived(const QByteArray byteArray);

public slots:
    void readLoop();
private:
    int opendevice_flag = 0;
    int ClaimInterface_flag = 0;

    int start_flag = 0;
    int touch_count =0;
    int touchUp = 0;
    bool IsHeartbeatPacket;
    bool KBConnectDongleStatus;
//    bool switch_inter = false;


    // 添加私有成员变量和方法
    const int VID = 0x0483;
    const int PID = 0x0010;
    libusb_context *context;
    libusb_device *device;
    libusb_device_handle *handle;
    libusb_device *findKeyboardDevice();

    receicerFuntion selectFuntion;
    bool running = false;
    QMutex usbMutex;
    QElapsedTimer timer;
    qint64 lastTime1 = 0;
    int is_consecutive = 1;

    void pollKeyboardData();
    int connectDevice();
    void releaseDevice();


};


#endif // USBKEYBOARDTHREAD_H
